package ying.cookie05;/**
 * ClassName: LastVisited
 * Package: ying.cookie05
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/10/5 13:44
 * @Version 1.0
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import ying.utils.CookieUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.查找一个名称为lastVisited的cookie
        Cookie cookie = CookieUtils.getCookie(request.getCookies(),"lastVisited");

        response.setContentType("text/html;charset=UTF-8");

        if (cookie == null) {
            response.getWriter().write("第一次访问");
        }else {
            //取出cookie中记录的时间,响应给浏览器
            String dataStr = cookie.getValue();
            //将日期进行解码
            String decodeDate = URLDecoder.decode(dataStr, "UTF-8");

            response.getWriter().write("上次访问时间为: " + decodeDate);
        }

        //无论是第一次,第二次,第三次,....第n次访问,都需要将当前系统时间设置到cookie,响应给浏览器
        String formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

        //再将日期放入cookie前,先进行编码,防止cookie不支持某些字符
        String encodeDate = URLEncoder.encode(formatDate, "UTF-8");

        Cookie lastVisitedCookie = new Cookie("lastVisited",encodeDate);
        lastVisitedCookie.setMaxAge(7* 24 * 60 * 60);
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
